{include file="$header" /}
<div class="mk-app-warp">
    <mk-table-header
        keyword-title="名称关键词搜索"
        :add-url="addUrl"
        :del-url="delUrl"
        :rows="rows"
        @del="del()"
        @add="openDrawer()"
        @search="searchData($event)">
    </mk-table-header>
    <el-table
        ref="table"
        :data="tableTree"
        v-loading="loading"
        :default-sort = "{prop: search.prop, order: search.order}"
        @sort-change="sortChange"
        @selection-change="checkSelected"
        @select-all="checkAll"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        default-expand-all>
        <el-table-column type="selection" width="55" :selectable="checkDisabled"></el-table-column>
        <el-table-column prop="title" label="名称" sortable="custom"></el-table-column >
        <el-table-column prop="status" label="状态" width="100px" sortable="custom">
            <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="status(scope.row)"
                    :disabled="scope.$index === 0 || editAuthority === false">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
            <template slot-scope="scope" v-if="scope.$index !== 0">
                <mk-table-public
                    :edit-url="editUrl"
                    :del-url="delUrl"
                    :push-url="addUrl"
                    :copy-url="addUrl"
                    @edit="openDrawer(scope.row)"
                    @del="del(scope.row)"
                    @push="parentAppend(scope.row)"
                    @copy="copy(scope.row)">
                </mk-table-public>
            </template>
        </el-table-column>
    </el-table>
</div>
{include file="admin_group/drawer" /}
{include file="$component" /}
<script>
    var menu = {:json_encode($menu)};
    new Vue({
        el: '#app',
        data() {
            return {
                rows: [],
                table: [],
                tableTree: [],
                tableTreeString: [],
                search:{
                    keyword: "",
                    prop: "title", 
                    order: "descending",
                },
                url: "adminGroup/index",
                addUrl: "adminGroup/save",
                delUrl: "adminGroup/delete",
                editUrl: "adminGroup/update",
                loading: false,
                expand: true,
                select: false,
                drawer: false,
                drawerData: {},
                drawerForm: {
                    pid: "",
                    title: "",
                    role: "",
                    status: 1,
                },
                drawerRules: {
                    pid: [
                        { required: true, message: '请选择父级', trigger: 'blur' },
                    ],
                    title: [
                        { required: true, message: '请输入组别名称', trigger: 'blur' },
                        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
                    ],
                },
                drawerLoading: false,
                // 树形菜单选择
                drawerMenu: menu,
                drawerMenuTree: tree.convert(menu),
                drawerProps: {
                    children: 'children',
                    label: 'title'
                },
                drawerTreeChecked: false,
                drawerTreeExpand: false,
            }
        },
        created () {
            this.getData();
        },
        computed: {
            editAuthority() {
                return authorityPath.indexOf(this.editUrl) !== -1;
            },
        },
        methods: {
            /**
             * 获取数据
             */
            getData() {
                let self     = this;
                self.loading = true;
                request.post(self.url, self.search, function(res) {
                    self.loading    = false;
                    self.table      = res.data;
                    self.tableTree  = tree.convert(self.table);
                });
            },
            sortChange(v) {
                this.search = Object.assign({}, this.search, {prop: v.prop , order: v.order});
            },
            /**
             * 向父类追加行
             * @param  {Object} row 当前行
             */     
            parentAppend(row) {
                let arr = JSON.parse(JSON.stringify(this.drawerForm));
                arr.pid = row.id;
                this.openDrawer(arr);
            },
            /**
             * 复制
             * @param  {Object} row 当前行
             */
            copy(row) {
                let arr = JSON.parse(JSON.stringify(row));
                delete(arr['id']);
                this.openDrawer(arr);
            },
            /**
             * 打开抽屉
             * @param  {Object} row 当前行
             */
            openDrawer(row = "") {
                let self = this;
                let parentList = []; //不包含本身及下属
                self.drawerData = row === "" ? JSON.parse(JSON.stringify(self.drawerForm)) : JSON.parse(JSON.stringify(row));
                self.table.forEach(function (item, index) {
                    // 下级不显示
                    if (item.id !== self.drawerData.id) {
                        parentList.push(item);
                    }
                })
                self.tableTreeString = tree.convertString(parentList);
                self.drawer = true;
            },
            /**
             * 保存内容
             */
            saveDrawer() {
                let self = this;
                self.$refs.drawerData.validate((valid) => {
                    if (valid) {
                        let requestUrl = typeof self.drawerData.id === 'undefined' ? self.addUrl : self.editUrl;
                        let roleSel    = self.$refs.tree.getCheckedKeys();
                        let rolePar    = self.$refs.tree.getHalfCheckedKeys();
                        let roleArr    = roleSel.concat(rolePar);
                        self.drawerLoading   = true;
                        self.drawerData.role = roleArr.join(',');
                        request.post(requestUrl, self.drawerData, function(res){
                            self.drawerLoading = false;
                            if (res.status === 'success') {
                                self.getData();
                                self.drawer = false;
                            } else {
                                self.$message({ showClose: true, message: res.message, type: res.status});
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            /**
             * 行删除、批量删除
             * @param  {Object} row 当前行
             */
            del(row = "") {
                let self = this;
                let ids  = row === "" ? common.arrayColumn(self.rows,'id') : [row.id]; 
                self.$confirm('确定删除吗？', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.post(self.delUrl, {'ids': ids}, function(res){
                        if (res.status === 'success') {
                            self.getData();
                        } else {
                            self.$message({ showClose: true, message: res.message, type: res.status});
                        }
                    });
                }).catch(() => {});
            },
            /**
             * 状态管理
             * @param  {Object} row 当前行
             */
            status(row) {
                let self = this;
                request.post(self.editUrl, {id: row.id, value: row.status, field: 'status'}, function(res) {
                    if (res.status != 'success') {
                        self.$message({ showClose: true, message: res.message, type: res.status});
                        self.getData();
                    }
                });
            },
            /**
             * 关键词搜索
             * @param  {Object} value 搜索内容
             */
            searchData(value) {
                this.search = Object.assign({}, this.search, {keyword: value.keyword});
            },
            /**
             * 选中行
             * @param  {Object} rows 多行数
             */
            checkSelected(rows) {
                this.rows = rows;
            },
            /**
             * 行不可选中
             * @param  {Object} row   [description]
             */
            checkDisabled(row) {
                return row.pid === 0 ? false : true;
            },
            /**
             * 选中所有行，只有树形结构才需要这样处理
             */
            checkAll() {
                let self    = this;
                let table  = self.$refs.table;
                self.select = self.select ? false : true;
                self.table.forEach(function (item, index){
                    if (item.pid !== 0) table.toggleRowSelection(item, self.select);
                });
            },
            /**
             * 抽屉的菜单权限样式处理
             */
            drawerTreeContent(h, { node, data, store }) {
                if (data.pid === 0 ) {
                    var classname = "";
                } else {
                    var classname = typeof data.children === "undefined" ||  data.children.length === 0 ? "levelname" :"";
                }
                return h("p", { class: classname }, node.label );
            },
            drawerTreeCss() {
                var levelName = document.getElementsByClassName("levelname");
                for (var i = 0; i < levelName.length; i++) {
                    levelName[i].parentNode.style.cssFloat = "left";
                    levelName[i].parentNode.style.styleFloat = "left";
                    levelName[i].parentNode.style.paddingLeft = "18px";
                }
            },
            /**
             * 抽屉的菜单权限全选处理
             */
            drawerTreeCheckedAll(){
                let keys = [];
                if(this.drawerTreeChecked === true){
                    keys = common.arrayColumn(this.drawerMenu, 'id');
                }
                this.$refs.tree.setCheckedKeys(keys);
            },
            /**
             * 抽屉的菜单权限展开/折叠
             */
            drawerTreeExpandAll(){
                let keys  = common.arrayColumn(this.drawerMenu, 'id');
                let self = this;
                keys.forEach(function(item, index){
                    self.$refs.tree.store.nodesMap[item].expanded = self.drawerTreeExpand;
                })
                this.$nextTick(()=>{
                    this.drawerTreeCss();
                })
            },
        },
        watch: {
            drawer(v) {
                this.$nextTick(()=>{
                    if(v){
                        let self    = this;
                        let checked = this.drawerData.role.split(',');
                        checked.forEach(function (item, index) {
                            self.$refs.tree.setChecked(item, true);
                        })
                        this.drawerTreeChecked = false;
                    } else {
                        // 重置表单
                        this.$refs.drawerData.resetFields();
                    }

                })
            },
            search() {
                this.getData();
            }
        }
    })
</script>
{include file="$footer" /}